package com.viewshine.nettydemo.springBeanMethod.nettyClient;

import com.alibaba.fastjson.JSON;
import com.viewshine.nettydemo.springBeanMethod.nettyVo.NettyRequest;
import com.viewshine.nettydemo.springBeanMethod.nettyVo.NettyRespose;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BasicsEchoClientHandler
 * @Author rhb
 * @Description SpringBean管理 客户端处理器
 * @Date 2019-01-17 16:20
 * @Version 1.0
 **/
@Slf4j
@ChannelHandler.Sharable
public class SpringEchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 请求模型
     */
    private NettyRequest nettyRequest;

    /**
     * 返回模型
     */
    private NettyRespose nettyRespose = new NettyRespose();


    public SpringEchoClientHandler(NettyRequest nettyRequest) {
        this.nettyRequest = nettyRequest;
    }

    /**
     * 连接上服务器
     *
     * @param ctx
     * @throws Exception
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送的字符串
        String cmd = JSON.toJSONString(nettyRequest.getSendData());
        log.debug("发送命令【{}】", cmd);
        byte[] bytes = cmd.getBytes();
        ByteBuf clientMessage = Unpooled.buffer(bytes.length);
        clientMessage.writeBytes(bytes);
        ctx.writeAndFlush(clientMessage);
    }

    /**
     * @param ctx
     * @param byteBuf
     * @throws Exception
     */
    protected void messageReceived(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        try {
            byte[] req = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(req);
            String message = new String(req, "UTF-8");
            log.debug("结算到的SpringEchoServer返回数据【{}】", message);
            nettyRespose.setCode(200);
            nettyRespose.setData(message);
        } finally {
            ctx.close();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        nettyRespose.setCode(500);
        nettyRespose.setMsg("SpringEchoClientHandle处理器异常");
        cause.printStackTrace();
        ctx.close();
    }

    public NettyRespose getNettyRespose() {
        return nettyRespose;
    }
}
